const mongoose = require('mongoose')
const { ObjectId } = mongoose.Types
const { Address } = require('../../schema')

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()
const addressCollection = mongoose.model('address', Address)

function insertAddressList ({ userid, name, tel, province, city, county, addressDetail, isDefault }) {
    return new Promise(resolve => {
        const record = new addressCollection({
            userid,
            addressid: ObjectId(),
            name,
            tel,
            province,
            city,
            county,
            addressDetail,
            isDefault,
            isDelete: false
        })
        record.save().then(res => {
            resolve('添加地址成功')
        })
    })
}

function getAddressList (userid) {
    return new Promise(resolve => {
        addressCollection.find({
            userid,
            isDelete: false
        }).then(res => {
            resolve(res)
        }).catch(err => {
            resolve([])
        })
    })
}

function getAddressDetail (addressid) {
    return new Promise(resolve => {
        addressCollection.findOne({
            addressid
        }).then(res => {
            resolve(res)
        }).catch(err => {
            resolve('fail')
        })
    })
}

function modifyAddressList (data) {
    return new Promise(resolve => {
        addressCollection.updateOne({ addressid: data.addressid }, data).then(res => {
            if (res.modifiedCount) {
                resolve('修改地址信息成功')
            } else {
                resolve('地址信息保持不变')
            }
        }).catch(err => {
            resolve('地址信息修改失败')
        })
    })
}

function removeAddressList (addressid) {
    return new Promise(resolve => {
        addressCollection.updateOne({ addressid }, {
            isDelete: true
        }).then(res => {
            if (res.modifiedCount) {
                resolve('删除地址成功')
            } else {
                resolve('地址不存在')
            }
        }).catch(err => {
            resolve('删除地址失败')
        })
    })
}

module.exports = {
    getAddressList,
    insertAddressList,
    modifyAddressList,
    removeAddressList,
    getAddressDetail
}
